
package com.zjff.myshop.admin.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.zjff.myshop.admin.pojo.vo.FileUploadVO;
import com.zjff.myshop.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.Instant;
import java.util.HashSet;
import java.util.Set;


@CrossOrigin
@RestController
@Api(value = "v1", tags = "87.后台管理系统-文件上传")
@RequestMapping("/admin/v1")
@SaCheckLogin
public class AdminUploadController {
    private static final Logger logger = LoggerFactory.getLogger(AdminUserController.class);
    @Resource
    private StandardServletMultipartResolver standardServletMultipartResolver;

    @Value("${file.upload.location}") //         file:/D:/test/
    private String uploadLocation;
    @Value("${file.upload.path}") //         file:/D:/test/
    private String uploadPath;

    /**
     * 图片上传（单个）
     */
    @ApiOperation(value = "文件上传", notes = "上传单个文件 参数名为 \"multipartFile\"")
    @PostMapping(value = "/fileUpload")
    public Result<FileUploadVO> fileUpload(MultipartFile multipartFile, String oldFile) throws IOException {
        String path = uploadLocation + "temp/";
        logger.info("multipartFile:{}", multipartFile);
        //判断上传的文件是否为空
        if (multipartFile == null || multipartFile.isEmpty()) {
            return Result.error("请选选择文件再上传，参数名multipartFile");
        }
        String contentType = multipartFile.getContentType();
        logger.info("文件类型:{}", contentType);
        //获取文件名
        String fileName = multipartFile.getOriginalFilename();
        //获取文件后缀名 没有点符号
        String fileSuffix = FileUtil.extName(fileName);
        //限制文件类型
        Set<String> set = new HashSet<>();
        set.add("jpg");
        set.add("png");
        set.add("xls");
        set.add("xlsx");
        if (!CollectionUtil.contains(set, fileSuffix)) {
            return Result.error("当前只支持上传:jpg png xls xlsx类型");
        }

        //使用时间戳+3位随机数作为新的文件名
        long milli = Instant.now().toEpochMilli();
        String randomNumbers = RandomUtil.randomNumbers(3);
        //生成新的文件名
        String newFileName = milli + randomNumbers + "." + fileSuffix;
        //创建文件夹,如果存在则不创建
        FileUtil.mkdir(path);
        //文件路径
        String filePath = path + newFileName;
        try {
            if (StrUtil.isNotEmpty(oldFile)) {
                //删除文件
                FileUtil.del(path + oldFile);
            }
            //实现文件存储
            FileUtil.writeBytes(multipartFile.getBytes(), filePath);
            FileUploadVO fileUploadVO = new FileUploadVO();
            //文件访问的Url路径
            String url = String.format("%stemp/%s", uploadPath.replace("*", ""), newFileName);
            fileUploadVO.setUrlPath(url);
            //文件存放的完整路径
            fileUploadVO.setFileName(newFileName);

            return Result.ok(fileUploadVO);

        } catch (IOException e) {
            logger.error("文件上传失败 报错信息:" + e);
            return Result.error("文件上传失败，请管理员查看控制台日志信息。");
        }
    }

//    public Result<FileUploadVO> upload(HttpServletRequest httpServletRequest, @RequestParam("file") MultipartFile file) throws URISyntaxException {
//
//        String fileName = file.getOriginalFilename();
//        String suffixName = null; //后缀名
//        if (fileName != null) {
//            suffixName = fileName.substring(fileName.lastIndexOf("."));
//        }
//        //生成文件名称通用方法
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
//        Random r = new Random();
//        String newFileName = sdf.format(new Date()) + r.nextInt(100) + suffixName;
//        File fileDirectory = new File(Constants.FILE_UPLOAD_DIC);
//        //创建文件
//        File destFile = new File(Constants.FILE_UPLOAD_DIC + newFileName);
//        try {
//            if (!fileDirectory.exists()) {
//                if (!fileDirectory.mkdir()) {
//                    throw new IOException("文件夹创建失败,路径为：" + fileDirectory);
//                }
//            }
//            file.transferTo(destFile);
//            Result resultSuccess = Result.ok();
//            FileUploadVO fileUploadVO = new FileUploadVO();
//            List<String> urlList = new ArrayList<>();
//            String url = "/uploads/" + newFileName;
//            urlList.add(url);
//            fileUploadVO.setUrls(urlList.toArray(new String[0]));
//            resultSuccess.setData(fileUploadVO);
//            return resultSuccess;
//        } catch (IOException e) {
//            e.printStackTrace();
//            return Result.error("文件上传失败");
//        }
//    }

    /**
     * 图片上传（多个）  待测试...
     */
//    @SuppressWarnings("unchecked")
//    @PostMapping(value = "/upload/files")
//    @ApiOperation(value = "多图上传", notes = "多个图片上传")
//    public Result<FileUploadVO> uploadV2(HttpServletRequest httpServletRequest) throws URISyntaxException {
//
//        List<MultipartFile> multipartFiles = new ArrayList<>(8);
//        if (standardServletMultipartResolver.isMultipart(httpServletRequest)) {
//            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) httpServletRequest;
//            Iterator<String> iter = multiRequest.getFileNames();
//            int total = 0;
//            while (iter.hasNext()) {
//                if (total > 5) {
//                    return Result.error("最多上传5张图片");
//                }
//                total += 1;
//                MultipartFile file = multiRequest.getFile(iter.next());
//                multipartFiles.add(file);
//            }
//        }
//        if (CollectionUtils.isEmpty(multipartFiles)) {
//            return Result.error("参数异常");
//        }
//        if ( multipartFiles.size() > 5) {
//            return Result.error("最多上传5张图片");
//        }
//        ArrayList<String> urlList = new ArrayList<>(multipartFiles.size());
//        for (MultipartFile multipartFile : multipartFiles) {
//            String fileName = multipartFile.getOriginalFilename();
//            String suffixName = null;
//            if (fileName != null) {
//                suffixName = fileName.substring(fileName.lastIndexOf("."));
//            }
//            //生成文件名称通用方法
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
//            Random r = new Random();
//            String newFileName = sdf.format(new Date()) + r.nextInt(100) + suffixName;
//            File fileDirectory = new File(Constants.FILE_UPLOAD_DIC);
//            //创建文件
//            File destFile = new File(Constants.FILE_UPLOAD_DIC + newFileName);
//            try {
//                if (!fileDirectory.exists()) {
//                    if (!fileDirectory.mkdir()) {
//                        throw new IOException("文件夹创建失败,路径为：" + fileDirectory);
//                    }
//                }
//                multipartFile.transferTo(destFile);
//                urlList.add("/uploads/" + newFileName);
//            } catch (IOException e) {
//                e.printStackTrace();
//                return Result.error("文件上传失败");
//            }
//        }
//        Result resultSuccess = Result.ok();
//
//        FileUploadVO fileUploadVO = new FileUploadVO();
//        fileUploadVO.setUrls(urlList.toArray(new String[0]));
//        resultSuccess.setData(fileUploadVO);
//        return resultSuccess;
//    }
}
